package com.quectel.core.module.workorder.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.core.module.workorder.dao.WorkOrderDirectDao;
import com.quectel.core.module.workorder.dto.WorkOrderDirectDto;
import com.quectel.core.module.workorder.entity.WorkOrderDirectEntity;
import com.quectel.core.module.workorder.service.WorkOrderDirectService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/03/09 13:38
 */
@DubboService
public class WorkOrderDirectServiceImpl implements WorkOrderDirectService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkOrderDirectServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> WORK_ORDER_DIRECT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "WORK_ORDER_DIRECT_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<WorkOrderDirectDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(WORK_ORDER_DIRECT_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private WorkOrderDirectDao workOrderDirectDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private DeptPersonService deptPersonService;


    @Override
    public WorkOrderDirectDto selectOne(Long villageId, Byte category, Byte type) {
        WorkOrderDirectEntity workOrderDirectEntity = workOrderDirectDao.selectOne(new LambdaQueryWrapper<WorkOrderDirectEntity>()
                .eq(WorkOrderDirectEntity::getVillageId, villageId)
                .eq(WorkOrderDirectEntity::getCategory, category).eq(WorkOrderDirectEntity::getType, type)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        WorkOrderDirectDto workOrderDirectDto = CopyUtils.copyObj(workOrderDirectEntity, WorkOrderDirectDto.class);
        paddingField(workOrderDirectDto);
        return workOrderDirectDto;
    }

    @Override
    public WorkOrderDirectDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                WORK_ORDER_DIRECT_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public WorkOrderDirectDto selectById(Long id) {
        WorkOrderDirectEntity entity = workOrderDirectDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, WorkOrderDirectDto.class));
    }

    @Override
    public List<WorkOrderDirectDto> queryList(Map<String, Object> params) {
        List<WorkOrderDirectEntity> list = workOrderDirectDao.queryList(params);
        List<WorkOrderDirectDto> result = CopyUtils.copyList(list, WorkOrderDirectDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private WorkOrderDirectDto paddingField(WorkOrderDirectDto dto) {
        if (dto != null) {
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            dto.setVillage(villageDto);

            DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(dto.getDeptPersonId());
            dto.setDeptPerson(deptPersonDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return workOrderDirectDao.queryTotal(params);
    }

    @Override
    public Long save(WorkOrderDirectDto dto) {
        WorkOrderDirectEntity entity = CopyUtils.copyObj(dto, WorkOrderDirectEntity.class);
        entity.setId(Snowflake.nextId());
        workOrderDirectDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(WorkOrderDirectDto dto) {
        WorkOrderDirectEntity entity = CopyUtils.copyObj(dto, WorkOrderDirectEntity.class);

        workOrderDirectDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(WorkOrderDirectDto dto) {
        WorkOrderDirectEntity entity = CopyUtils.copyObj(dto, WorkOrderDirectEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, workOrderDirectDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        workOrderDirectDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
